import React, {Component} from 'react';
import E from 'wangeditor';

class UEditor extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editorContent: '',
            defaultValue: props.value,
        };
    }

    componentDidMount() {
        this.initEditor();
    }

    onChange = (content) => {
        this.props.onChange(content);
    }

    getContent = () => {
        return this.state.editorContent;
    }

    setContent = (content) => {
        this.state.editor.txt.html(content);
    }

    initEditor() {
        const elem = this.refs.editorElem;
        const editor = new E(elem);
        // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
        editor.customConfig.onchange = (html) => {
            this.setState({
                editorContent: html,
            });
            this.onChange(html);
        };
        editor.customConfig.uploadFileName = 'files[]';
        editor.customConfig.uploadImgServer = '/api/upload/editor';
        editor.customConfig.uploadImgParams = {token: sessionStorage.getItem('access_token')};
        editor.customConfig.zIndex = 100;
        editor.create();
        this.state.editor = editor;
        this.state.editor.txt.html(this.state.editorContent);
    }

    render() {
        return (
            <div ref="editorElem" style={{textAlign: 'left'}}/>
        );
    }
}

export default UEditor;
